#!/usr/bin/env bash
# scripts/gatekeeper-helper.sh
# macOS Gatekeeper helper menu
set -euo pipefail

title="Gatekeeper Helper"
separator="=============================================="

pause() {
  read -rp "按回车继续..."
}

print_header() {
  clear
  echo "$separator"
  echo "          $title"
  echo "$separator"
}

# 从 /Applications 列出最近 3 个 .app 并返回用户选定的路径
select_app() {
  local default_dir="/Applications"
  local -a apps
  # 按 kMDItemDateAdded（Finder 的 "Date Added"）排序
  IFS=$'\n' apps=($(
    find "${default_dir}" -maxdepth 1 -name "*.app" 2>/dev/null | while read app; do
      date_added=$(mdls -name kMDItemDateAdded -raw "$app" 2>/dev/null)
      if [[ -n "$date_added" && "$date_added" != "(null)" ]]; then
        echo "$date_added|$app"
      fi
    done | sort -rn | head -n 3 | cut -d'|' -f2
  ))
  
  if (( ${#apps[@]} == 0 )); then
    # 没有找到 .app，直接让用户输入
    read -erp "未检测到 .app，手动输入完整路径: " custom >&2
    echo "$custom"
    return
  fi

  # 交互信息输出到 stderr，避免被 $() 捕获
  echo "最近安装（修改时间最新）的 3 个应用：" >&2
  for i in "${!apps[@]}"; do
    local marker=""
    if (( i == 0 )); then
      marker=" [最新，默认]"
    fi
    echo "$((i+1))) ${apps[$i]##*/}${marker}" >&2
  done
  echo "c) 其他路径" >&2
  read -erp "请选择 [1-${#apps[@]}/c，回车=1]: " choice >&2
  
  # 回车默认选择第一个（最新的）
  if [[ -z "$choice" ]]; then
    echo "${apps[0]}"  # 只有这个输出到 stdout，被捕获
  elif [[ "$choice" =~ ^[1-3]$ ]] && (( choice>=1 && choice<=${#apps[@]} )); then
    echo "${apps[$((choice-1))]}"
  else
    read -erp "输入完整路径: " custom >&2
    echo "$custom"
  fi
}

remove_quarantine() {
  echo ""
  echo "== 去除 quarantine 标记 =="
  echo ""
  local target
  target=$(select_app)
  
  if [[ -e "$target" ]]; then
    echo "正在递归删除扩展属性: $target"
    sudo xattr -cr "$target"
    echo "✅ 已完成。"
  else
    echo "❌ 路径不存在！"
  fi
  pause
}

show_xattr() {
  echo ""
  echo "== 查看扩展属性 =="
  echo ""
  read -erp "输入文件或目录完整路径: " target
  
  if [[ -e "$target" ]]; then
    echo "扩展属性列表："
    xattr -l "$target" || echo "（无扩展属性）"
  else
    echo "❌ 路径不存在！"
  fi
  pause
}

adhoc_sign() {
  echo ""
  echo "== ad-hoc 临时签名 =="
  echo ""
  local target
  target=$(select_app)
  
  if [[ -d "$target" && "$target" == *.app ]]; then
    echo "开始临时签名（可能需要几分钟）: $target"
    sudo codesign --force --deep --sign - "$target"
    echo "✅ 签名完成。"
  else
    echo "❌ 请输入有效 .app 路径！"
  fi
  pause
}

zip_test() {
  echo ""
  echo "== 测试 .zip 完整性 =="
  echo ""
  read -erp "输入 .zip 完整路径: " target
  
  if [[ -f "$target" && "$target" == *.zip ]]; then
    echo "测试压缩包完整性..."
    if unzip -t "$target"; then
      echo "✅ 压缩包完整。"
    else
      echo "❌ 压缩包损坏！"
    fi
  else
    echo "❌ 请输入有效 .zip 路径！"
  fi
  pause
}

gatekeeper_toggle() {
  echo ""
  echo "== 开/关 Gatekeeper =="
  echo ""
  echo "当前状态:"
  sudo spctl --status || true
  echo ""
  read -erp "选择操作 [d=关闭 / e=开启 / 回车取消]: " choice
  
  case "$choice" in
    d|D) 
      sudo spctl --master-disable
      echo "✅ 已关闭 Gatekeeper（不推荐长期关闭）"
      ;;
    e|E) 
      sudo spctl --master-enable
      echo "✅ 已开启 Gatekeeper"
      ;;
    *)   
      echo "已取消。"
      ;;
  esac
  pause
}

# 主循环菜单
while true; do
  print_header
  cat <<EOF

1) 去除 quarantine 标记（最常用）
2) 查看扩展属性
3) ad-hoc 临时签名 .app
4) 测试 .zip 完整性
5) 开/关 Gatekeeper
q) 退出

EOF
  read -erp "请选择: " opt
  
  case "$opt" in
    1) remove_quarantine ;;
    2) show_xattr ;;
    3) adhoc_sign ;;
    4) zip_test ;;
    5) gatekeeper_toggle ;;
    q|Q) echo "Bye~"; exit 0 ;;
    *)   echo "❌ 无效输入！"; pause ;;
  esac
done

